﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;
using System.Collections;

namespace VSM.Parts
{
    public partial class CreateDO : System.Web.UI.Page
    {
        #region Fields
        private GeneralFunctions GF = null;
        private string TblHeaderName = "ODLN";
        private string TblLineName = "DLN1";
        private string dbType = string.Empty;
        //private string TblLineName1 = "DLN3";
        private string CurrentPageUrl = "/Business/Parts/Sales/CreateDO.aspx";
        private string HeaderKeyName = "DocEntry";
        private String TargetPageUrl = "/Business/Parts/Sales/ARInvoice.aspx";
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.Private);

            if (Session[Utils.AppConstants.ID_User] == null
                || Session[Utils.AppConstants.Password] == null
                || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("../../../Login.aspx");
            }
            dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            if (!IsPostBack)
            {
                this.txtDeliveryTime.Text = DateTime.Now.ToString("hh:mm tt");

                ClearScreen();

                // Get Warehouse
                DataTable dtWhs = GF.GetWarehouseByDealerDepartment(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), Utils.AppConstants.PARTS);
                // Get Vat Group
                DataTable dtVatGroup = GF.GetVatGroupByCategory(dbType, "O");

                String BaseEntry = Request.QueryString["base_entry"];
                String doId = Request.QueryString["do_id"];

                if (!String.IsNullOrEmpty(doId))
                {
                    LoadData(doId, ConvertDocType.Get2String(DocType.DELIVERY));
                    if (lblStatus.Text == "Closed")
                        SetScreenStatus("Close");
                    else if (lblStatus.Text == "OPen")
                        SetScreenStatus("Update");
                }
                else if (!String.IsNullOrEmpty(BaseEntry))
                {
                    LoadData(BaseEntry, Request.QueryString["base_type"]);
                }
                else
                {
                    LoadDefault();
                    SetScreenStatus("New");
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvSO.PageIndex = e.NewPageIndex;
            DataTable tblIPO = (DataTable)Session["DOTable"];
            BindData(tblIPO);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["DOTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString())) dicItem.Remove(rupdate[0]["ItemCode"].ToString());

                        }
                        tb.Rows.Remove(rupdate[0]);
                        int liNo = 1;
                        foreach (DataRow dr in tb.Rows)
                        {
                            dr["No"] = liNo;
                            liNo++;
                        }
                    }
                    this.grvSO.EditIndex = -1;
                    BindData((DataTable)Session["DOTable"]);
                    updateTableTotalPrice();
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";

                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                DataTable dtWhs = GF.GetWarehouseByDealerDepartment(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), Utils.AppConstants.PARTS);
                DataTable dtVatGroup = GF.GetVatGroupByCategory(dbType, "O");
                // Load Model
                DropDownList ddlModel = (DropDownList)e.Row.FindControl("ddlModel");
                Label txtModel = (Label)e.Row.FindControl("txtModel");
                if (ddlModel != null)
                {
                    ddlModel.DataSource = GF.GetModelList(dbType);
                    ddlModel.DataValueField = "Code";
                    ddlModel.DataTextField = "Name";
                    ddlModel.DataBind();
                    ddlModel.Items.Insert(0, "");
                    if (txtModel != null) ddlModel.SelectedValue = txtModel.Text;
                }
                // Load Product
                DropDownList ddlProduct = (DropDownList)e.Row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, txtModel.Text);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");
                    Label txtProduct = (Label)e.Row.FindControl("txtProduct");
                    if (txtProduct != null) ddlProduct.SelectedValue = txtProduct.Text;
                }
                // Load Color
                DropDownList ddlColor = (DropDownList)e.Row.FindControl("ddlColor");
                if (ddlColor != null)
                {
                    ddlColor.DataSource = GF.GetColorList(dbType);
                    ddlColor.DataValueField = "Code";
                    ddlColor.DataTextField = "Name";
                    ddlColor.DataBind();
                    ddlColor.Items.Insert(0, "");
                    Label txtColorCode = (Label)e.Row.FindControl("txtCorlorCode");
                    if (txtColorCode != null) ddlColor.SelectedValue = txtColorCode.Text;
                }

                // Load Whs
                DropDownList ddlWhs = (DropDownList)e.Row.FindControl("ddlWhs");
                if (ddlWhs != null)
                {
                    ddlWhs.DataSource = dtWhs;
                    ddlWhs.DataValueField = "WhsCode";
                    ddlWhs.DataTextField = "WhsName";
                    ddlWhs.DataBind();
                    HiddenField hdnWhsCode = (HiddenField)e.Row.FindControl("hdnWhsCode");
                    if (hdnWhsCode != null) ddlWhs.SelectedValue = hdnWhsCode.Value;
                }

                // Load Vat Group
                DropDownList ddlVatGrp = (DropDownList)e.Row.FindControl("ddlVatGroup");
                if (ddlVatGrp != null)
                {
                    ddlVatGrp.DataSource = dtVatGroup;
                    ddlVatGrp.DataValueField = "Code";
                    ddlVatGrp.DataTextField = "Name";
                    ddlVatGrp.DataBind();
                    HiddenField hdnVatGroup = (HiddenField)e.Row.FindControl("hdnVatGroup");
                    if (hdnVatGroup != null)
                    {
                        ddlVatGrp.SelectedValue = hdnVatGroup.Value;
                        DataRow[] rRate = dtVatGroup.Select("Code='" + hdnVatGroup.Value + "'");
                        if (rRate.Length > 0)
                        {
                            HiddenField hdnVatPrcnt = (HiddenField)e.Row.FindControl("hdnVatPrcnt");
                            hdnVatPrcnt.Value = rRate[0]["Rate"].ToString();
                        }
                    }
                }

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtUnitPrice_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtUnitPrice = (TextBox)row.FindControl("txtUnitPrice");
                if (txtUnitPrice.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Price');", true);
                    txtUnitPrice.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["DOTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["PriceBefDi"] = txtUnitPrice.Text;
                        updateRowTotalPrice(rupdate[0], "PriceBefDi");
                    }
                }

                this.grvSO.EditIndex = -1;

                BindData(tb);
                updateTableTotalPrice();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        protected void txtDiscountPrcnt_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtDiscount = (TextBox)row.FindControl("txtDiscountPrcnt");
                if (txtDiscount.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Discount');", true);
                    txtDiscount.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["DOTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["DiscPrcnt"] = txtDiscount.Text;
                        updateRowTotalPrice(rupdate[0], "DiscPrcnt");
                    }
                }

                this.grvSO.EditIndex = -1;

                BindData(tb);
                updateTableTotalPrice();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtDiscount_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtDiscount = (TextBox)row.FindControl("txtDiscount");
                if (txtDiscount.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Discount');", true);
                    txtDiscount.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["DOTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["U_Discount"] = txtDiscount.Text;
                        updateRowTotalPrice(rupdate[0], "U_Discount");
                    }
                }

                this.grvSO.EditIndex = -1;

                BindData(tb);
                updateTableTotalPrice();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtIncentiveDsc_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtIncentiveDsc = (TextBox)row.FindControl("txtIncentiveDsc");
                if (txtIncentiveDsc.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Incentive Discount.');", true);
                    txtIncentiveDsc.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["DOTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["U_IncentiveDiscount"] = GF.FormatNumeric(GF.ResetFormatNumeric(txtIncentiveDsc.Text), "SumDec");
                        updateRowTotalPrice(rupdate[0], "U_IncentiveDiscount");
                    }
                }

                this.grvSO.EditIndex = -1;

                BindData(tb);
                updateTableTotalPrice();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["DOTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        updateRowTotalPrice(rupdate[0], "Quantity");
                    }
                }

                this.grvSO.EditIndex = -1;
                BindData(tb);
                updateTableTotalPrice();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtShipDate_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtShipDate = (TextBox)row.FindControl("txtShipDate");
                if (txtShipDate.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Ship Date');", true);
                    txtShipDate.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["DOTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0) rupdate[0]["ShipDate"] = txtShipDate.Text;
                }

                this.grvSO.EditIndex = -1;
                BindData(tb);
                updateTableTotalPrice();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            Session["DOTable"] = tblData;
            this.grvSO.DataSource = tblData;
            this.grvSO.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                    DataTable tblRDR1 = (DataTable)Session["DOTable"];
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectItem":
                            this.lblError.Visible = false;
                            if (tblRDR1 != null)
                            {
                                Dictionary<string, string> dicItem = Session["ChosenItem"] != null ? (Dictionary<string, string>)Session["ChosenItem"] : null;
                                if (dicItem != null)
                                {
                                    foreach (KeyValuePair<string, string> item in dicItem)
                                    {
                                        LoadItem(poDate, ref tblRDR1, dbType, item.Key, "1", "0", "");
                                    }

                                    if (tblRDR1.Rows.Count > 0)
                                        foreach (DataRow dr in tblRDR1.Rows)
                                            updateRowTotalPrice(dr, "");
                                }
                            }
                            //ReLoad Data
                            BindData(tblRDR1);
                            updateTableTotalPrice();
                            break;

                        case "SelectBP":
                            ViewState["rowindex"] = -1;
                            this.lblError.Visible = false;
                            GridViewRow row = Session["ChosenBP"] != null ? (GridViewRow)Session["ChosenBP"] : null;

                            this.txtCustomerCode.Text = ((Label)row.FindControl("lblCardCode")).Text;
                            this.txtCustomerName.Text = ((Label)row.FindControl("lblCardName")).Text;
                            this.txtContactPerson.Text = ((Label)row.FindControl("lblCntctPrsn")).Text;

                            if (tblRDR1 != null) tblRDR1.Rows.Clear();
                            Session["ChosenBP"] = null;
                            this.FileUploadControl.Enabled =
                            this.btnImport.Enabled =
                               this.txtItemCode.Enabled =
                            this.btnAddItems.Enabled = true;
                            break;

                        case "SelectDocList":
                            GridViewRow rowDocList = Session["ChosenDocList"] != null ? (GridViewRow)Session["ChosenDocList"] : null;
                            string soId = ((Label)rowDocList.FindControl("lblDocNum")).Text;
                            string doctype = ((Label)rowDocList.FindControl("lblDocType")).Text;
                            this.hdnDocEntry.Value = soId;
                            LoadData(soId, doctype);
                            break;
                        case "SelectDraftDocList":
                            GridViewRow rowDraftDocList = Session["SelectDraftDocList"] != null ? (GridViewRow)Session["SelectDraftDocList"] : null;
                            string docEntry = ((Label)rowDraftDocList.FindControl("lblDocEntry")).Text;
                            string doctypeSO = ((Label)rowDraftDocList.FindControl("lblDocType")).Text;
                            this.hdnBaseType.Value = doctypeSO;
                            this.hdnDocEntry.Value = docEntry;
                            this.hdnIsDraft.Value = "1";
                            LoadDraftData(docEntry, "DocEntry");
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        private void LoadItem(DateTime poDate, ref DataTable tblSQ, string dbType, string key, string quantity, string discount, string price)
        {
            GetDefault defaultWS = new GetDefault();

            DataSet defaultInfo = null;
            try
            {
                defaultInfo = defaultWS.GetPartsDefaultLineInfo(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(),
                    this.txtCustomerCode.Text, key, 1, poDate, Utils.AppConstants.PARTS, "2");
            }
            catch
            {

            }
            if (defaultInfo != null)
            {
                DataTable dtWhs = GF.GetWarehouseByDealerDepartment(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), Utils.AppConstants.PARTS);
                DataTable dtVatGroup = GF.GetVatGroupByCategory(dbType, "O");
                DataRow rowNew = tblSQ.NewRow();
                rowNew["No"] = (tblSQ.Rows.Count + 1).ToString();
                rowNew["ItemCode"] = key;
                rowNew["Dscription"] = defaultInfo.Tables[0].Rows[0]["ItemName"];
                rowNew["U_Model"] = defaultInfo.Tables[0].Rows[0]["U_Model"];
                rowNew["U_Product"] =
                rowNew["U_Color"] = string.Empty;
                rowNew["Quantity"] = quantity;
                if (discount.Length > 0)
                {
                    rowNew["DiscPrcnt"] = discount;
                }
                else
                {
                    rowNew["DiscPrcnt"] = 0;
                }
                if (price.Length == 0)
                {
                    if (defaultInfo != null && defaultInfo.Tables.Count > 0 && defaultInfo.Tables[0].Rows.Count > 0)
                    {
                        rowNew["PriceBefDi"] = defaultInfo.Tables[0].Rows[0]["UnitPrice"];
                    }
                    else
                    {
                        rowNew["PriceBefDi"] = 0;
                    }
                }
                else
                {
                    rowNew["PriceBefDi"] = price;
                }
                if (this.chkPromotion.Checked == false)
                {
                    rowNew["U_PromotionPrice"] = 0;
                }
                else
                {
                    rowNew["U_PromotionPrice"] = rowNew["PriceBefDi"];
                }
                rowNew["ShipDate"] = this.txtPostingDate.Text;
                rowNew["VatGroup"] = dtVatGroup.Rows.Count > 0 ? dtVatGroup.Rows[0]["Code"].ToString() : string.Empty;
                rowNew["VatPrcnt"] = dtVatGroup.Rows.Count > 0 ? dtVatGroup.Rows[0]["Rate"].ToString() : "0";
                rowNew["VatSum"] =
                rowNew["U_Discount"] =
                rowNew["U_IncentiveDiscount"] = 0;
                rowNew["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;

                DataRow[] rExist = tblSQ.Select("ItemCode='" + key + "'");
                if (rExist.Length == 0)
                {
                    tblSQ.Rows.Add(rowNew);
                }
                if (chkPromotion.Checked)
                {
                    this.grvSO.Columns[7].Visible = false;
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>z
        private void UpdatePrice()
        {
            try
            {

                BindData((DataTable)Session["DOTable"]);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblIPO"></param>
        /// <param name="poDate"></param>
        /// <param name="itemCode"></param>
        /// <param name="itemName"></param>
        /// <param name="venderCode"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        //private DataTable AddNewItem(DataTable tblSO, DataRow drDefaultLine, string ItemCode, string Dscription, string Model, string Color)
        //{
        //    try
        //    {
        //        if (drDefaultLine != null && drDefaultLine.ItemArray.Length > 0)
        //        {
        //            DataRow rowNew = tblSO.NewRow();
        //            rowNew["ItemCode"] = ItemCode;
        //            rowNew["Dscription"] = Dscription;
        //            rowNew["U_Model"] = Model;
        //            rowNew["U_Color"] = Color;
        //            rowNew["Quantity"] = 1;

        //            rowNew["PriceBefDi"] = drDefaultLine["UnitPrice"];
        //            rowNew["DiscPrcnt"] = drDefaultLine["Discount"];
        //            rowNew["PriceBefDi"] = drDefaultLine["PriceAfDi"];

        //            rowNew["TaxCode"] = drDefaultLine["TaxCode"];
        //            rowNew["VatPrcnt"] = drDefaultLine["TaxRate"];
        //            rowNew["WhsCode"] = drDefaultLine["WhsCode"];
        //            rowNew["ShipDate"] = txtDeliveryDate.Text;

        //            DataRow[] rCheck = tblSO.Select("ItemCode='" + ItemCode + "'");
        //            if (rCheck.Length == 0)
        //            {
        //                tblSO.Rows.Add(rowNew);
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        this.lblError.Text = ex.Message;
        //        this.lblError.Visible = true;
        //    }
        //    return tblSO;
        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tb"></param>
        //private void CalcTotal(DataTable tb)
        //{
        //    try
        //    {
        //        double documentTotal = 0;
        //        double gstTotal = 0;
        //        double subTotal = 0;
        //        foreach (DataRow row in tb.Rows)
        //        {
        //            subTotal += double.Parse(row["LineTotal"].ToString());
        //            if (row["Rate"] != null && row["Rate"].ToString().Length > 0)
        //            {
        //                gstTotal += (double.Parse(row["LineTotal"].ToString()) * double.Parse(row["Rate"].ToString())) / 100;
        //            }
        //            else
        //            {
        //                gstTotal += (double.Parse(row["LineTotal"].ToString()) * 8.25) / 100;
        //            }
        //        }
        //        documentTotal += subTotal + gstTotal;

        //        this.lblTaxAmount.Text = string.Format("{0:C}", Math.Round(gstTotal, 2));
        //        this.lblSubTotal.Text = string.Format("{0:C}", Math.Round(subTotal, 2));
        //        this.lblPaymentTotal.Text = string.Format("{0:C}", Math.Round(documentTotal, 2));
        //    }
        //    catch (Exception ex)
        //    {
        //        string alert = "alert('Error: " + ex.Message + " ');";
        //        ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
        //    }
        //}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="poDate"></param>
        /// <param name="itemCode"></param>
        /// <param name="venderCode"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        //private DataSet GetDataItem(DateTime poDate, string itemCode, string venderCode, double quantity)
        //{
        //    try
        //    {
        //        MasterData obj = new MasterData();
        //        DataSet ds = new DataSet();
        //        ds = null; // obj.GetItem(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode, poDate, itemCode, venderCode, quantity);
        //        return ds;
        //    }
        //    catch (Exception ex)
        //    {
        //        this.lblError.Text = ex.Message;
        //        this.lblError.Visible = true;
        //    }
        //    return null;
        //}

        private void BuildSRNT(ref DataTable dtSRNT, string ItemCode, string SysNumber, string DistNumber, string InDate, string Notes,
            double Quantity, string WhsCode, string DocType, string DocEntry, string DocLineNum)
        {
            if (dtSRNT == null)
            {
                dtSRNT = new DataTable("SRNT");
                dtSRNT.Columns.Add("ItemCode");
                dtSRNT.Columns.Add("SysNumber");    // Default
                dtSRNT.Columns.Add("DistNumber");   // VIN Number
                dtSRNT.Columns.Add("InDate");       // Get default
                dtSRNT.Columns.Add("Quantity");     // 1
                dtSRNT.Columns.Add("WhsCode");      // Default
                dtSRNT.Columns.Add("DocType");      // 13
                dtSRNT.Columns.Add("DocEntry");     // Get from Incoming Payment No.
                dtSRNT.Columns.Add("DocLineNum");   // 1
                dtSRNT.Columns.Add("Notes");   // 
                //dtSRNT.Columns.Add("BSubLineNo");   // LineNo
            }

            DataRow drSRNT = dtSRNT.NewRow();
            drSRNT["ItemCode"] = ItemCode;      // INV1
            drSRNT["SysNumber"] = SysNumber;
            drSRNT["DistNumber"] = DistNumber;   // VIN Number
            drSRNT["InDate"] = Utils.AppConstants.ConvertToDate(InDate).ToString("yyyyMMdd");
            drSRNT["Quantity"] = Quantity;       // INV1
            drSRNT["WhsCode"] = WhsCode;         // INV1
            drSRNT["DocType"] = DocType;         // INV1
            drSRNT["DocEntry"] = DocEntry;       // INV1
            drSRNT["DocLineNum"] = DocLineNum;   // INV1
            drSRNT["Notes"] = Notes;
            //drSRNT["BSubLineNo"] = BSubLineNo; // INV1
            dtSRNT.Rows.Add(drSRNT);
        }

        public String _collectData(bool isDraft, string draftObjType)
        {
            try
            {
                if (isDraft)
                {
                    TblHeaderName = "ODRF";
                    TblLineName = "DRF1";
                }
                //Update table header
                DataTable dtHeader = new DataTable(TblHeaderName);
                //dtHeader.Columns.Add("DocEntry");
                //dtHeader.Columns.Add("DocNum");
                if (!this.hdnIsUpdate.Value.Equals("true"))
                {
                    dtHeader.Columns.Add("Series"); // 6
                    dtHeader.Columns.Add("DocStatus");
                }
                dtHeader.Columns.Add("DocDate");
                dtHeader.Columns.Add("DocDueDate");
                dtHeader.Columns.Add("TaxDate");
                dtHeader.Columns.Add("CardCode");
                if (draftObjType != "20")
                {
                    dtHeader.Columns.Add("CardName");
                }
                dtHeader.Columns.Add("Comments");
                dtHeader.Columns.Add("SlpCode");
                dtHeader.Columns.Add("GrosProfit");
                dtHeader.Columns.Add("VatSum");
                dtHeader.Columns.Add("NumAtCard");

                dtHeader.Columns.Add("DiscSum");
                dtHeader.Columns.Add("DiscPrcnt");
                //UDF
                dtHeader.Columns.Add("U_ContactPerson");
                dtHeader.Columns.Add("U_DealerID");
                dtHeader.Columns.Add("U_Department");
                dtHeader.Columns.Add("U_DebitNote");
                dtHeader.Columns.Add("U_Issue");
                dtHeader.Columns.Add("U_SOType");

                dtHeader.Columns.Add("U_DeliveryTime");
                dtHeader.Columns.Add("U_BillNBR");
                if (draftObjType == "20")
                {
                    dtHeader.Columns.Add("U_CustomerID");
                }

                dtHeader.Columns.Add("U_SONBR");
                if (isDraft)
                {
                    dtHeader.Columns.Add("ObjType");
                }
                DataRow drHeader = dtHeader.NewRow();
                if (isDraft)
                {
                    drHeader["ObjType"] = draftObjType;//"15";
                }
                if (hdnIsUpdate.Value.Equals("true"))
                {
                    //drHeader["DocEntry"] =
                    //drHeader["DocNum"] = int.Parse(txtDONo.Text);
                }
                else
                {
                    drHeader["Series"] = 6;
                    drHeader["DocStatus"] = "O";
                }
                drHeader["DocDate"] = Utils.AppConstants.ConvertToDate(txtPostingDate.Text).ToString("yyyyMMdd");
                drHeader["DocDueDate"] = Utils.AppConstants.ConvertToDate(txtDeliveryDate.Text).ToString("yyyyMMdd");
                drHeader["TaxDate"] = Utils.AppConstants.ConvertToDate(txtDocDate.Text).ToString("yyyyMMdd");
                if (draftObjType != "20")
                {
                    drHeader["CardCode"] = txtCustomerCode.Text;
                    drHeader["CardName"] = txtCustomerName.Text.Trim();
                }
                else
                {
                    drHeader["CardCode"] = "VS";
                    drHeader["U_CustomerID"] = txtCustomerCode.Text;
                }
                drHeader["Comments"] = txtRemarks.Text;
                drHeader["SlpCode"] = ddlSaleMan.SelectedValue;
                drHeader["GrosProfit"] = GF.ResetFormatNumeric(string.IsNullOrEmpty(lblSubTotal.Text) ? "0" : lblSubTotal.Text);
                drHeader["VatSum"] = GF.ResetFormatNumeric(string.IsNullOrEmpty(lblTaxAmount.Text) ? "0" : lblTaxAmount.Text);
                drHeader["NumAtCard"] = txtSONo.Text;
                // UDF
                drHeader["U_ContactPerson"] = txtContactPerson.Text.Trim();
                drHeader["U_DealerID"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                drHeader["U_Department"] = Utils.AppConstants.PARTS;
                drHeader["U_DebitNote"] = this.txtDebitNoteNo.Text.Trim();
                drHeader["U_SONBR"] = this.txtVSMSONumber.Text.Trim();
                drHeader["U_DeliveryTime"] = this.ddlTime.SelectedValue.ToString();
                drHeader["U_BillNBR"] = this.txtBillNumber.Text.Trim();
                if (this.chkPromotion.Checked)
                {
                    drHeader["U_Issue"] = "KM";
                }
                else
                {
                    drHeader["U_Issue"] = "XB";
                }
                drHeader["U_SOType"] = this.hdnSOType.Value;
                updateDiscPrcnt(drHeader);
                dtHeader.Rows.Add(drHeader);

                DataSet ds = new DataSet("DS");
                dtHeader.TableName = TblHeaderName;
                ds.Tables.Add(dtHeader.Copy());

                DataTable dt = new DataTable(TblLineName);
                //dt.Columns.Add("DocEntry");
                if (draftObjType != "20")
                {
                    dt.Columns.Add("LineNum");
                    //dt.Columns.Add("LineStatus");
                }
                dt.Columns.Add("LineStatus");
                dt.Columns.Add("ItemCode");
                dt.Columns.Add("Dscription");
                dt.Columns.Add("Quantity");
                dt.Columns.Add("ShipDate");
                dt.Columns.Add("Price");
                if (draftObjType != "20")
                {
                    // dt.Columns.Add("LineTotal");
                }
                dt.Columns.Add("PriceBefDi");
                dt.Columns.Add("VatGroup");
                dt.Columns.Add("VatPrcnt");
                dt.Columns.Add("WhsCode");

                dt.Columns.Add("U_Color");
                dt.Columns.Add("U_Model");
                dt.Columns.Add("U_Product");
                //
                dt.Columns.Add("VatSum");
                dt.Columns.Add("U_Discount");
                dt.Columns.Add("U_IncentiveDiscount");
                dt.Columns.Add("U_PromotionPrice");
                if (draftObjType != "20")
                {
                    if (!String.IsNullOrEmpty(hdnBaseType.Value))
                    {
                        dt.Columns.Add("BaseEntry");
                        dt.Columns.Add("BaseLine");
                        dt.Columns.Add("BaseType");
                    }
                }
                DataTable dtContents = (DataTable)Session["DOTable"];
                int liNo = 0;
                foreach (DataRow dr in dtContents.Rows)
                {
                    DataRow rowNew = dt.NewRow();
                    if (hdnIsUpdate.Value.Equals("true"))
                    {
                        // rowNew["DocEntry"] = int.Parse(this.txtDONo.Text);
                    }
                    if (draftObjType != "20")
                    {
                        rowNew["LineNum"] = liNo;
                    }
                    rowNew["LineStatus"] = "O";
                    rowNew["ItemCode"] = dr["ItemCode"];
                    rowNew["Dscription"] = dr["Dscription"];
                    rowNew["Quantity"] = dr["Quantity"];
                    rowNew["ShipDate"] = Utils.AppConstants.ConvertToDate(dr["ShipDate"].ToString().Substring(0, 10)).ToString("yyyyMMdd");
                    rowNew["Price"] = dr["Price"];
                    if (draftObjType != "20")
                    {
                        //rowNew["LineTotal"] = dr["LineTotal"];
                    }
                    rowNew["PriceBefDi"] = dr["PriceBefDi"];
                    rowNew["WhsCode"] = dr["WhsCode"];

                    rowNew["VatGroup"] = dr["VatGroup"];
                    rowNew["VatPrcnt"] = dr["VatPrcnt"];
                    rowNew["VatSum"] = dr["VatSum"];

                    rowNew["U_Discount"] = dr["U_Discount"];
                    rowNew["U_IncentiveDiscount"] = dr["U_IncentiveDiscount"];

                    rowNew["U_Color"] = dr["U_Color"];
                    rowNew["U_Model"] = dr["U_Model"];
                    rowNew["U_Product"] = dr["U_Product"];
                    if (dtContents.Columns.Contains("U_PromotionPrice"))
                    {
                        rowNew["U_PromotionPrice"] = dr["U_PromotionPrice"];
                    }
                    if (draftObjType != "20")
                    {
                        if (!String.IsNullOrEmpty(hdnBaseType.Value))
                        {
                            rowNew["BaseEntry"] = dr["BaseEntry"];
                            rowNew["BaseLine"] = dr["BaseLine"];
                            rowNew["BaseType"] = dr["BaseType"];
                        }
                    }
                    dt.Rows.Add(rowNew);
                    liNo++;
                }
                Array arrContentsCols = new string[] { "Quantity", "PriceBefDi", "Price", "VatPrcnt", "VatSum", "U_Discount", "U_IncentiveDiscount" };
                //Array arrContentsCols = new string[] { "Quantity", "PriceBefDi", "Price", "VatPrcnt", "VatSum", "U_Discount", "U_IncentiveDiscount", "LineTotal" };// Columns need to reset format numeric
                ds.Tables.Add(GF.ResetFormatNumeric(dt, arrContentsCols).Copy()); // Order details

                #region Build Freight Charge has commented
                #endregion
                if (!isDraft)
                {
                    if (draftObjType != "20")
                    {
                        DataTable dtSRNT = (DataTable)Session["tblPARTSRNT"];
                        if (dtSRNT != null)
                        {
                            foreach (DataRow dr in dt.Rows)
                            {
                                DataRow[] rDocLineNum = dtSRNT.Select("No=" + (int.Parse(dr["LineNum"].ToString()) + 1).ToString());
                                if (rDocLineNum.Length > 0)
                                {
                                    for (int i = 0; i < rDocLineNum.Length; i++)
                                    {
                                        rDocLineNum[i]["DocLineNum"] = dr["LineNum"];
                                        rDocLineNum[i]["DocType"] = ConvertDocType.Get2String(DocType.DELIVERY);
                                        rDocLineNum[i]["InDate"] = Utils.AppConstants.ConvertToDate(rDocLineNum[i]["InDate"].ToString()).ToString("yyyyMMdd");
                                    }
                                }
                            }
                            ds.Tables.Add(dtSRNT.Copy());
                        }
                    }
                }
                string objType = string.Empty;
                if (!isDraft)
                {
                    objType = ConvertDocType.Get2String(DocType.DELIVERY);
                }
                else
                {
                    objType = "112";
                }
                DocumentXML objInfo = new DocumentXML();
                return objInfo.ToXMLStringFromDS(objType, ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }

        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();

                if (this.hdnStatus.Value == "C")
                {
                    LinkButton lnkDelete = (LinkButton)myRow.FindControl("lnkDelete");
                    TextBox txtQuantity = (TextBox)myRow.FindControl("txtOrderQuantity");
                    TextBox txtUnitPrice = (TextBox)myRow.FindControl("txtUnitPrice");
                    TextBox txtDiscount = (TextBox)myRow.FindControl("txtDiscount");
                    TextBox txtIncentiveDsc = (TextBox)myRow.FindControl("txtIncentiveDsc");
                    TextBox txtShipDate = (TextBox)myRow.FindControl("txtShipDate");
                    ImageButton imgShipDate = (ImageButton)myRow.FindControl("imgShipDate");

                    if (lnkDelete != null) lnkDelete.Enabled = false;
                    if (imgShipDate != null) imgShipDate.Enabled = false;

                    if (txtQuantity != null)
                    {
                        txtQuantity.ReadOnly = true;
                        txtQuantity.BackColor = System.Drawing.Color.Transparent;
                        txtQuantity.BorderStyle = BorderStyle.None;
                    }
                    if (txtUnitPrice != null)
                    {
                        txtUnitPrice.ReadOnly = true;
                        txtUnitPrice.BackColor = System.Drawing.Color.Transparent;
                        txtUnitPrice.BorderStyle = BorderStyle.None;
                    }
                    if (txtDiscount != null)
                    {
                        txtDiscount.ReadOnly = true;
                        txtDiscount.BackColor = System.Drawing.Color.Transparent;
                        txtDiscount.BorderStyle = BorderStyle.None;
                    }
                    if (txtIncentiveDsc != null)
                    {
                        txtIncentiveDsc.ReadOnly = true;
                        txtIncentiveDsc.BackColor = System.Drawing.Color.Transparent;
                        txtIncentiveDsc.BorderStyle = BorderStyle.None;
                    }
                    if (txtShipDate != null)
                    {
                        txtShipDate.ReadOnly = true;
                        txtShipDate.BackColor = System.Drawing.Color.Transparent;
                        txtShipDate.BorderStyle = BorderStyle.None;
                    }
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtPODate_TextChanged(object sender, EventArgs e)
        {
            try
            {
                //Check Valid Date
                Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text.Trim());
                this.FileUploadControl.Enabled =
                           this.btnImport.Enabled =
                           this.txtItemCode.Enabled =
                this.btnAddItems.Enabled = true;
            }
            catch
            {
                this.FileUploadControl.Enabled =
                       this.txtItemCode.Enabled =
                           this.btnImport.Enabled =
                this.btnAddItems.Enabled = false;
            }
            UpdatePrice();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtItemCode_TextChanged(object sender, EventArgs e)
        {
            DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
            DataTable tblRDR1 = (DataTable)Session["DOTable"];
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

            this.lblError.Visible = false;
            if (tblRDR1 != null)
            {
                LoadItem(poDate, ref tblRDR1, dbType, this.txtItemCode.Text.Trim(), "1", "0", "");

                if (tblRDR1.Rows.Count > 0)
                {
                    foreach (DataRow dr in tblRDR1.Rows)
                    {
                        updateRowTotalPrice(dr, "");
                    }
                }
            }
            //ReLoad Data
            BindData(tblRDR1);
            updateTableTotalPrice();
        }
        /// <summary>
        /// 
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                if (string.IsNullOrEmpty(txtPostingDate.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Posting Date.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtPostingDate.Focus();
                    return;
                }

                if (string.IsNullOrEmpty(txtDocDate.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Document Date.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtDocDate.Focus();
                    return;
                }

                if (string.IsNullOrEmpty(txtDeliveryDate.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Delivery Date.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtDeliveryDate.Focus();
                    return;
                }

                if (string.IsNullOrEmpty(txtCustomerCode.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Customer Code.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtCustomerCode.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(this.txtVSMSONumber.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing SO Number.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtVSMSONumber.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(this.txtDebitNoteNo.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Debit Note No.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtDebitNoteNo.Focus();
                    return;
                }
                else
                {
                    string lsNumAtCard = GF.GetSingleValue(dbType, " SELECT U_DebitNote FROM ODLN WHERE U_DebitNote = '" + this.txtDebitNoteNo.Text.Trim() + "'", "U_DebitNote");
                    if (!string.IsNullOrEmpty(lsNumAtCard))
                    {
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('The Debit Note No. existed.','');", true);
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                        this.txtDebitNoteNo.Focus();
                        return;
                    }
                }
                String requestXML = _collectData(false, "");
                if (requestXML == "") return;

                Transaction ts = new Transaction();
                DataSet ds = ts.CreateMarketingDocument(requestXML, ConvertDocType.Get2String(DocType.DELIVERY), this.hdnDocEntry.Value, hdnIsUpdate.Value.Equals("true"), dbType);

                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    //Close Draft
                    if (this.hdnIsDraft.Value == "1" && this.hdnDocEntry.Value.Length > 0)
                    {
                        ts.CloseCancelDocument(ConvertDocType.Get2String(DocType.ALL_DRAFT), this.hdnDocEntry.Value, true, dbType); // thangnv edited on 2014/07/22
                    }
                    //Create GRPO Draft for Dealer
                    requestXML = _collectData(true, "20");
                    if (requestXML == "") return;
                    bool isUpdate = false;
                    MasterData obj = new MasterData();
                    string docEntry = string.Empty;
                    DataSet returnDoc = obj.GetDraftMarketingDocument_ReturnDS(this.hdnOldDebitNote.Value.Trim(), dbType, "U_DebitNote");
                    if (returnDoc != null && returnDoc.Tables.Count > 0 && returnDoc.Tables[0].Rows.Count > 0)
                    {
                        isUpdate = true;
                        docEntry = returnDoc.Tables[0].Rows[0]["DocEntry"].ToString();
                    }
                    ds = ts.CreateMarketingDocument(requestXML, ConvertDocType.Get2String(DocType.GOODS_RECEIPT_PO), docEntry, isUpdate, dbType);

                    if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                    {
                        Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                        Session["requestXML"] = requestXML;
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                    }
                    else
                    {
                        Session["successMessage"] = "Operation complete sucessful!";
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                        ClearScreen();
                    }

                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseCancel(true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
            CloseCancel(false);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isClose"></param>
        private void CloseCancel(bool isClose)
        {
            try
            {
                Transaction obj = new Transaction();
                string error = string.Empty;
                //if (_isPO == "1")
                {
                    //error = obj.CloseCancelPO(int.Parse(_docEntry), _companyCode, isClose, false);
                }
                //else
                {
                    //error = obj.CloseCancelPO(int.Parse(_docEntry), _companyCode, isClose, true);
                }
                if (error.Length == 0)
                {
                    this.lblError.Text = "Operation complete successful!";
                }
                else
                {
                    this.lblError.Text = error;
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;
        }

        private DataTable BuildContents(DataTable dtContent)
        {
            DataTable dt = new DataTable(TblLineName);
            dt.Columns.Add("No");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Product");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("PriceBefDi");
            dt.Columns.Add("DiscPrcnt");
            dt.Columns.Add("Price");
            dt.Columns.Add("UomCode");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("OpenQty");
            dt.Columns.Add("ShipDate");
            dt.Columns.Add("LineTotal");

            dt.Columns.Add("VatGroup");
            dt.Columns.Add("VatPrcnt");
            dt.Columns.Add("VatSum");
            // UDF
            dt.Columns.Add("U_Discount");
            dt.Columns.Add("U_IncentiveDiscount");
            dt.Columns.Add("U_PromotionPrice");

            dt.Columns.Add("TotalAfDisc");
            dt.Columns.Add("Total");
            dt.Columns.Add("WhsCode");

            dt.Columns.Add("DocEntry");
            dt.Columns.Add("LineNum");

            dt.Columns.Add("BaseType");
            dt.Columns.Add("BaseEntry");
            dt.Columns.Add("BaseLine");

            if (dtContent != null)
            {
                foreach (DataRow dr in dtContent.Rows)
                {
                    DataRow row = dt.NewRow();
                    row["No"] = dr["No"];
                    row["ItemCode"] = dr["ItemCode"];
                    row["Dscription"] = dr["Dscription"];
                    row["U_Model"] = dr["U_Model"];
                    row["U_Product"] = dr["U_Product"];
                    row["U_Color"] = dr["U_Color"];
                    row["PriceBefDi"] = dr["PriceBefDi"];
                    row["DiscPrcnt"] = dr["DiscPrcnt"];
                    row["Price"] = dr["Price"];
                    row["UomCode"] = dr["UomCode"];
                    row["Quantity"] = dr["Quantity"];
                    row["OpenQty"] = dr["OpenQty"];
                    row["ShipDate"] = dr["ShipDate"];
                    row["LineTotal"] = dr["LineTotal"];
                    row["VatGroup"] = dr["VatGroup"];
                    row["VatPrcnt"] = dr["VatPrcnt"];
                    row["VatSum"] = dr["VatSum"];
                    // UDF
                    row["U_Discount"] = GF.FormatNumeric(GF.ResetFormatNumeric(dr["U_Discount"].ToString()), "SumDec");
                    row["U_IncentiveDiscount"] = GF.FormatNumeric(GF.ResetFormatNumeric(dr["U_IncentiveDiscount"].ToString()), "SumDec");
                    row["U_PromotionPrice"] = GF.FormatNumeric(dr["U_PromotionPrice"].ToString(), "SumDec");
                    // Total
                    row["TotalAfDisc"] = CalculateTotalAfDisc(row);
                    row["Total"] = CalculateTotal(row);
                    row["WhsCode"] = dr["WhsCode"];
                    row["DocEntry"] = dr["DocEntry"];
                    row["LineNum"] = dr["LineNum"];
                    row["BaseType"] = dr["BaseType"];
                    row["BaseEntry"] = dr["BaseEntry"];
                    row["BaseLine"] = dr["BaseLine"];
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }
        protected void LoadDraftData(string keyValue, string keyName)
        {
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            MasterData ts = new MasterData();
            DataSet returnDoc = ts.GetDraftMarketingDocument_ReturnDS(keyValue, dbType, keyName);

            DataTable dtHeader = returnDoc.Tables[0];
            DataTable dtContents = BuildContents(returnDoc.Tables[1]);
            DataRow dr = dtHeader.Rows[0];

            this.txtDONo.Text = dr["DocNum"].ToString();
            this.txtCustomerCode.Text = dr["CardCode"].ToString();
            this.txtCustomerName.Text = dr["CardName"].ToString();
            txtPostingDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDate"], new CultureInfo("es-US")));
            txtDocDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["TaxDate"], new CultureInfo("es-US")));
            txtDeliveryDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDueDate"], new CultureInfo("es-US")));
            this.txtContactPerson.Text = dr["U_ContactPerson"].ToString();
            txtRemarks.Text = dr["Comments"].ToString();
            txtSONo.Text = dr["NumAtCard"].ToString();
            this.txtDebitNoteNo.Text = dr["U_DebitNote"].ToString();
            this.hdnOldDebitNote.Value = dr["U_DebitNote"].ToString();
            this.txtVSMSONumber.Text = dr["U_SONBR"].ToString();
            this.txtBillNumber.Text = dr["U_BillNBR"].ToString();
            this.ddlTime.SelectedValue = dr["U_DeliveryTime"].ToString();

            if (dr["DocStatus"].ToString().Equals("C"))
            {
                this.lblStatus.Text = "Closed";
                SetScreenStatus("Close");
            }
            else if (dr["DocStatus"].ToString().Equals("O"))
            {
                SetScreenStatus("New");
            }
            // Binding Sale Man
            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlSaleMan, dr["SlpCode"].ToString());
            foreach (DataRow row in dtContents.Rows)
            {
                row["BaseEntry"] = row["BaseEntry"]; ;
                row["BaseLine"] = row["BaseLine"];
                row["BaseType"] = row["BaseType"]; //this.hdnBaseType.Value;
                row["ShipDate"] = DateTime.Parse((String.IsNullOrEmpty(row["ShipDate"].ToString()) ? txtDeliveryDate.Text : row["ShipDate"].ToString())).ToString("dd/MM/yyyy");
                updateRowTotalPrice(row, "");
            }
            // Remove Items not Payment yet
            DataTable tempContents = dtContents.Copy();

            // Get Freight Charge
            BindData(dtContents);
            updateTableTotalPrice();
        }

        protected void LoadData(String doId, string NewDocType)
        {
            hdnBaseType.Value = String.Empty;
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            Transaction ts = new Transaction();
            DataSet returnDoc = null;
            if (NewDocType != ConvertDocType.Get2String(DocType.DELIVERY)) // Incase copy from SO
                returnDoc = ts.GetMarketingDocument_OpenStatus(NewDocType, doId, dbType);
            else
                returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, doId, dbType);

            if (returnDoc == null) returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, "1", dbType);

            if (returnDoc == null || returnDoc.Tables.Count < 2)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('No record found!','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return;
            }

            DataTable dtHeader = returnDoc.Tables[0];
            DataTable dtContents = BuildContents(returnDoc.Tables[1]);
            DataRow dr = dtHeader.Rows[0];

            this.txtDONo.Text = dr["DocNum"].ToString();
            this.txtCustomerCode.Text = dr["CardCode"].ToString();
            this.txtCustomerName.Text = dr["CardName"].ToString();
            txtPostingDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDate"], new CultureInfo("es-US")));
            txtDocDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["TaxDate"], new CultureInfo("es-US")));
            txtDeliveryDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDueDate"], new CultureInfo("es-US")));
            this.txtContactPerson.Text = dr["U_ContactPerson"].ToString();
            txtRemarks.Text = dr["Comments"].ToString();
            txtSONo.Text = dr["NumAtCard"].ToString();
            this.txtDebitNoteNo.Text = dr["U_DebitNote"].ToString();
            this.hdnOldDebitNote.Value = dr["U_DebitNote"].ToString();
            this.txtVSMSONumber.Text = dr["U_SONBR"].ToString();
            this.txtBillNumber.Text = dr["U_BillNBR"].ToString();
            this.ddlTime.SelectedValue = dr["U_DeliveryTime"].ToString();
            this.hdnDocEntry.Value = dr["DocEntry"].ToString();
            this.hdnSOType.Value = dr["U_SOType"].ToString();
            if (dr["DocStatus"].ToString().Equals("C"))
            {
                this.lblStatus.Text = "Closed";
                SetScreenStatus("Close");
            }
            else if (dr["DocStatus"].ToString().Equals("O"))
            {
                this.lblStatus.Text = "Open";
                if (NewDocType != ConvertDocType.Get2String(DocType.DELIVERY))
                {
                    txtDONo.Text = string.Empty;
                    txtSONo.Text = dr["DocNum"].ToString();
                    SetScreenStatus("New");
                }
                else SetScreenStatus("Update");
            }
            if (dr["U_Issue"].ToString() == "KM")
            {
                this.chkPromotion.Checked = true;
                this.grvSO.Columns[7].Visible = false;
            }
            if (dr["U_OrderConfirm"].ToString() == "20")//Recaived
            {
                this.txtDebitNoteNo.Enabled = false;
                this.txtBillNumber.Enabled = false;
                this.txtVSMSONumber.Enabled = false;
                this.txtDeliveryTime.Enabled = false;
                this.ddlTime.Enabled = false;
                this.txtPostingDate.Enabled = false;
                this.txtDeliveryDate.Enabled = false;
                this.txtDocDate.Enabled = false;
                this.btnAddItems.Enabled = false;
                this.FileUploadControl.Enabled = false;
                this.btnImport.Enabled = false;
                this.txtItemCode.Enabled = false;
                this.lblGRPOStatus.Text = "Received.";
                this.grvSO.Enabled = false;
            }
            else if (dr["U_OrderConfirm"].ToString() == "21")//Printed
            {
                this.lblGRPOStatus.Text = "Printed";
                this.grvSO.Enabled = true;
                this.btnPrint.Enabled = false;
            }
            else //Pending
            {
                this.lblGRPOStatus.Text = "Pending.";
                this.grvSO.Enabled = true;
                this.btnPrint.Enabled = true;
            }
            // Binding Sale Man
            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlSaleMan, dr["SlpCode"].ToString());

            if (ConvertDocType.Get2String(DocType.DELIVERY) != NewDocType) //In this case: copy from Sales Order
            {
                hdnBaseType.Value = NewDocType;

                foreach (DataRow row in dtContents.Rows)
                {
                    row["Quantity"] = row["OpenQty"];
                    updateRowTotalPrice(row, "");
                    row["BaseEntry"] = doId;
                    row["BaseType"] = NewDocType;
                    row["BaseLine"] = row["LineNum"];
                    row["ShipDate"] = txtDeliveryDate.Text;
                }
                // Remove Items not Payment yet
                DataTable tempContents = dtContents.Copy();

            }
            else
            {
                foreach (DataRow row in dtContents.Rows)
                {
                    row["ShipDate"] = Convert.ToDateTime((String.IsNullOrEmpty(row["ShipDate"].ToString()) ? txtDeliveryDate.Text : row["ShipDate"].ToString())).ToString("dd/MM/yyyy");
                    updateRowTotalPrice(row, "");
                }
            }
            // Get Freight Charge
            BindData(dtContents);
            updateTableTotalPrice();
        }

        protected void LoadDefault()
        {
            this.lblStatus.Text = "Open";
            this.txtPostingDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDeliveryDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDocDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDONo.Text =
            this.txtSONo.Text =
            this.txtCustomerCode.Text =
            this.txtCustomerName.Text =
            this.txtContactPerson.Text =
            hdnBaseType.Value = string.Empty;
            // Bind Data Sale Man
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlSaleMan, "-1");

            DataTable dtContents = BuildContents(null);
            BindData(dtContents);
        }

        private double CalculateVatSum(DataRow dr)
        {
            double TotalAfDisc = 0, vatPrcnt = 0;
            TotalAfDisc = GF.Object2Double(GF.ResetFormatNumeric(dr["TotalAfDisc"].ToString()), "SumDec");
            vatPrcnt = GF.Object2Double(GF.ResetFormatNumeric(dr["VatPrcnt"].ToString()), "SumDec");
            return (TotalAfDisc * vatPrcnt) / 100;
        }

        private double CalculateTotalAfDisc(DataRow dr)
        {
            double LineTotal = 0, discAmnt = 0, incentiveDiscAmnt = 0;
            LineTotal = GF.Object2Double(GF.ResetFormatNumeric(dr["LineTotal"].ToString()), "SumDec");
            discAmnt = GF.Object2Double(GF.ResetFormatNumeric(dr["U_Discount"].ToString()), "SumDec");
            incentiveDiscAmnt = GF.Object2Double(GF.ResetFormatNumeric(dr["U_IncentiveDiscount"].ToString()), "SumDec");
            return LineTotal - (discAmnt + incentiveDiscAmnt);
        }

        private double CalculateTotal(DataRow dr)
        {
            double TotalAfDisc = 0, vatSumAmnt = 0;
            TotalAfDisc = GF.Object2Double(GF.ResetFormatNumeric(dr["TotalAfDisc"].ToString()), "SumDec");
            vatSumAmnt = GF.Object2Double(GF.ResetFormatNumeric(dr["VatSum"].ToString()), "SumDec");
            return TotalAfDisc + vatSumAmnt;
        }

        public void updateRowTotalPrice(DataRow row, string currColName)
        {
            try
            {
                double quantity = 0, unitPrice = 0.0, discount = 0, priceAfterDiscount = 0.0, totalBefDisc = 0;
                double VatPrcnt = 0, VatSum = 0, U_Discount = 0, U_IncentiveDiscount = 0, TotalAfDisc = 0, Total = 0;

                discount = GF.Object2Double(GF.ResetFormatNumeric(row["DiscPrcnt"].ToString()), "PercentDec");

                quantity = GF.Object2Double(GF.ResetFormatNumeric(row["Quantity"].ToString()), "QtyDec");
                unitPrice = GF.Object2Double(GF.ResetFormatNumeric(row["PriceBefDi"].ToString()), "PriceDec");
                // VatPrcnt, U_Discount, U_IncentiveDiscount
                VatPrcnt = GF.Object2Double(GF.ResetFormatNumeric(row["VatPrcnt"].ToString()), "PercentDec");
                U_Discount = GF.Object2Double(GF.ResetFormatNumeric(row["U_Discount"].ToString()), "SumDec");
                U_IncentiveDiscount = GF.Object2Double(GF.ResetFormatNumeric(row["U_IncentiveDiscount"].ToString()), "SumDec");

                priceAfterDiscount = GF.Object2Double((Object)(unitPrice * (100 - discount) / 100), "PriceDec");
                TotalAfDisc = GF.Object2Double((Object)(priceAfterDiscount * quantity), "SumDec");
                totalBefDisc = GF.Object2Double((Object)(unitPrice * quantity), "SumDec");

                VatSum = (totalBefDisc * VatPrcnt) / 100;
                // Total
                Total = (TotalAfDisc + VatSum);

                if (string.IsNullOrEmpty(currColName))
                    row["PriceBefDi"] = GF.FormatNumeric(unitPrice.ToString(), "PriceDec");

                row["Price"] = GF.FormatNumeric(priceAfterDiscount.ToString(), "PriceDec");
                row["LineTotal"] = GF.FormatNumeric(totalBefDisc.ToString(), "SumDec");
                if (string.IsNullOrEmpty(currColName) || currColName.Equals("PriceBefDi") || currColName.Equals("Quantity"))
                    row["Quantity"] = GF.FormatNumeric(quantity.ToString(), "QtyDec");

                row["TotalAfDisc"] = GF.FormatNumeric(TotalAfDisc.ToString(), "SumDec");
                row["VatSum"] = GF.FormatNumeric(VatSum.ToString(), "SumDec");
                row["Total"] = GF.FormatNumeric(Total.ToString(), "SumDec");
                if (dbType == "VSM")
                {
                    row["U_PromotionPrice"] = GF.FormatNumeric(row["U_PromotionPrice"].ToString(), "PriceDec");
                }
                row["DiscPrcnt"] = GF.FormatNumeric(discount.ToString(), "PriceDec");

            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void updateDiscPrcnt(DataRow dr)
        {
            double orderTotalBeforeDiscount = 0.0, U_DiscountTotal = 0.0, U_IncentiveDiscountTotal = 0.0;

            DataTable tbSQ = (DataTable)Session["DOTable"];

            foreach (DataRow row in tbSQ.Rows)
            {
                if (!"".Equals(row["ItemCode"]))
                {
                    // Subtotal
                    double total = GF.Object2Double((object)GF.ResetFormatNumeric(row["LineTotal"].ToString()), "SumDec");
                    orderTotalBeforeDiscount += total;
                    // Amount Disc.
                    double discAmnt = GF.Object2Double((object)GF.ResetFormatNumeric(row["U_Discount"].ToString()), "SumDec");
                    double IncentiveDisc = GF.Object2Double((object)GF.ResetFormatNumeric(row["U_IncentiveDiscount"].ToString()), "SumDec");
                    U_DiscountTotal += discAmnt;
                    U_IncentiveDiscountTotal += IncentiveDisc;
                }
            }
            dr["DiscSum"] = U_DiscountTotal + U_IncentiveDiscountTotal;
            dr["DiscPrcnt"] = ((U_DiscountTotal + U_IncentiveDiscountTotal) * 100) / orderTotalBeforeDiscount;
        }

        protected void updateTableTotalPrice()
        {
            double orderTotalBeforeDiscount = 0.0, orderTotal = 0.0, taxTotal = 0.0; //, freightCharge = 0.0;

            DataTable tbSO = (DataTable)Session["DOTable"];
            foreach (DataRow row in tbSO.Rows)
            {
                if (!"".Equals(row["ItemCode"]))
                {
                    // Subtotal
                    double total = GF.Object2Double((object)GF.ResetFormatNumeric(row["TotalAfDisc"].ToString()), "SumDec");
                    orderTotalBeforeDiscount += total;
                    // VatSum
                    double tax = GF.Object2Double((object)GF.ResetFormatNumeric(row["VatSum"].ToString()), "SumDec");
                    taxTotal += tax;
                }
            }
            this.lblSubTotal.Text = GF.FormatNumeric(orderTotalBeforeDiscount.ToString(), "SumDec");
            this.lblTaxAmount.Text = GF.FormatNumeric(taxTotal.ToString(), "SumDec");
            orderTotal = orderTotalBeforeDiscount + taxTotal; // +freightCharge;
            this.lblPaymentTotal.Text = GF.FormatNumeric(orderTotal.ToString(), "SumDec");
        }

        protected void ClearScreen()
        {
            // Bind Data Sale Man
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlSaleMan, "-1");

            CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
            txtPostingDate.Text.ToString(ci);
            txtDeliveryDate.Text.ToString(ci);
            txtDocDate.Text.ToString(ci);
            txtDONo.Text =
            txtSONo.Text =
            txtCustomerCode.Text =
            txtCustomerName.Text =
            txtRemarks.Text =
            this.hdnOldDebitNote.Value =
            this.txtBillNumber.Text =
            this.txtDebitNoteNo.Text =
            this.txtVSMSONumber.Text =
            txtContactPerson.Text = string.Empty;
            this.lblSubTotal.Text =
            this.lblTaxAmount.Text =
            this.lblPaymentTotal.Text = "0";
            //this.lblOtherFees.Text = "0";
            hdnBaseType.Value = String.Empty;
            this.chkPromotion.Checked = false;
            DataTable dt = new DataTable(TblLineName);
            dt.Columns.Add("No");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Product");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("PriceBefDi");
            dt.Columns.Add("DiscPrcnt");
            dt.Columns.Add("Price");
            dt.Columns.Add("UomCode");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("OpenQty");
            dt.Columns.Add("ShipDate");
            dt.Columns.Add("LineTotal");

            dt.Columns.Add("VatGroup");
            dt.Columns.Add("VatPrcnt");
            dt.Columns.Add("VatSum");
            // UDF
            dt.Columns.Add("U_Discount");
            dt.Columns.Add("U_IncentiveDiscount");
            dt.Columns.Add("U_PromotionPrice");

            dt.Columns.Add("TotalAfDisc");
            dt.Columns.Add("Total");
            dt.Columns.Add("WhsCode");

            dt.Columns.Add("DocEntry");
            dt.Columns.Add("LineNum");

            dt.Columns.Add("BaseType");
            dt.Columns.Add("BaseEntry");
            dt.Columns.Add("BaseLine");

            BindData(dt);
            SetScreenStatus("New");
            Session["tblPARTSRNT"] = null;
        }

        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    this.FileUploadControl.Enabled =
                           this.btnImport.Enabled =
                              this.txtItemCode.Enabled =
                    btnAddItems.Enabled =
                    btnPrint.Enabled =
                    btnCopyTo.Enabled = false;
                    btnCopyFrom.Enabled =
                    btnLastRecord.Enabled =
                    btnSelectBP.Enabled =
                    btnSave.Enabled =
                    btnCancel.Enabled = true;
                    hdnIsUpdate.Value = "false";
                    hdnStatus.Value = "O";
                    break;

                case "Update":
                    btnSelectBP.Enabled =
                         this.FileUploadControl.Enabled =
                            this.btnImport.Enabled =
                               this.txtItemCode.Enabled =
                    btnAddItems.Enabled =
                    btnSave.Enabled =
                    btnCancel.Enabled =
                    btnPrint.Enabled =
                    btnCopyFrom.Enabled =
                    btnCopyTo.Enabled = true;
                    hdnIsUpdate.Value = "true";
                    hdnStatus.Value = "O";
                    break;

                case "Close":
                    btnSelectBP.Enabled =
                        this.btnDraft.Enabled =
                         this.FileUploadControl.Enabled =
                            this.btnImport.Enabled =
                               this.txtItemCode.Enabled =
                    btnAddItems.Enabled =
                    btnSave.Enabled =
                    btnCancel.Enabled =
                    btnCopyFrom.Enabled =
                    btnCopyTo.Enabled = false;
                    btnLastRecord.Enabled =
                    btnPrint.Enabled = true;
                    hdnStatus.Value = "C";
                    break;
            }
        }

        protected void lnkOSRI_Click(object sender, EventArgs e)
        {
            try
            {
                if (hdnBaseType != null && hdnBaseType.Value.Equals(ConvertDocType.Get2String(DocType.DELIVERY))) return;
                GridViewRow gr = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;

                Label lblNo = (Label)gr.FindControl("lblNo");
                Label lblItemCode = (Label)gr.FindControl("lblItemCode");
                HiddenField hdnWhsCode = (HiddenField)gr.FindControl("hdnWhsCode");
                string popup = "OpenOSRI('" + lblItemCode.Text + "','" + hdnWhsCode.Value + "','" + lblNo.Text + "')";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", popup, true);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void btnCopyTo_Click(object sender, EventArgs e)
        {
            Response.Redirect(TargetPageUrl + "?base_type=" + ConvertDocType.Get2String(DocType.DELIVERY) + "&base_entry=" + txtDONo.Text);
        }

        protected void btnLastRecord_Click(object sender, EventArgs e)
        {
            GetDefault fGetDefault = new GetDefault();
            string lsDONo = fGetDefault.GetMaxDocEntry(
                Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER,
                Session[Utils.AppConstants.ID_Dealer].ToString(),
                Utils.AppConstants.PARTS,
                ConvertDocType.Get2String(DocType.DELIVERY),
                TblHeaderName, HeaderKeyName
            );
            if (txtDONo.Text.CompareTo(lsDONo) != 0) Response.Redirect(CurrentPageUrl + "?do_id=" + lsDONo);
        }

        protected void ddlModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
                if (ddlModel.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Model');", true);
                    ddlModel.Focus();
                    return;
                }
                Label txtModel = (Label)row.FindControl("txtModel");
                txtModel.Text = ddlModel.SelectedValue;

                // Load Product
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, ddlModel.SelectedValue);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");

                    Label txtProduct = (Label)row.FindControl("txtProduct");
                    txtProduct.Text = ddlProduct.SelectedValue;
                    SetItem(row);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Product');", true);
                    ddlProduct.Focus();
                    return;
                }

                Label txtProduct = (Label)row.FindControl("txtProduct");
                txtProduct.Text = ddlProduct.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlColor_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlColor = (DropDownList)row.FindControl("ddlColor");
                if (ddlColor.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Color');", true);
                    ddlColor.Focus();
                    return;
                }

                Label txtCorlor = (Label)row.FindControl("txtCorlorCode");
                txtCorlor.Text = ddlColor.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlWhs_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlWhs = (DropDownList)row.FindControl("ddlWhs");
                if (ddlWhs.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a warehouse');", true);
                    ddlWhs.Focus();
                    return;
                }

                HiddenField hdnWhsCode = (HiddenField)row.FindControl("hdnWhsCode");
                if (hdnWhsCode != null && !string.IsNullOrEmpty(hdnWhsCode.Value))
                {
                    hdnWhsCode.Value = ddlWhs.SelectedValue;
                    DataTable tblQUT1 = (DataTable)Session["DOTable"];
                    Label lblNo = (Label)row.FindControl("lblNo");
                    DataRow[] rowUpdate = tblQUT1.Select("No=" + lblNo.Text);
                    if (rowUpdate.Length > 0) rowUpdate[0]["WhsCode"] = hdnWhsCode.Value;
                    BindData(tblQUT1);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlVatGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                DataTable dtVatGroup = GF.GetVatGroupByCategory(dbType, "O");
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlVatGroup = (DropDownList)row.FindControl("ddlVatGroup");
                if (ddlVatGroup.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Tax Code.');", true);
                    ddlVatGroup.Focus();
                    return;
                }

                HiddenField hdnVatGroup = (HiddenField)row.FindControl("hdnVatGroup");
                if (hdnVatGroup != null && !string.IsNullOrEmpty(hdnVatGroup.Value))
                {
                    hdnVatGroup.Value = ddlVatGroup.SelectedValue;
                    DataTable tblQUT1 = (DataTable)Session["DOTable"];
                    Label lblNo = (Label)row.FindControl("lblNo");
                    //
                    DataRow[] rowUpdate = tblQUT1.Select("No=" + lblNo.Text);
                    if (rowUpdate.Length > 0)
                    {
                        rowUpdate[0]["VatGroup"] = hdnVatGroup.Value;
                        DataRow[] rRate = dtVatGroup.Select("Code='" + hdnVatGroup.Value + "'");
                        if (rRate.Length > 0)
                        {
                            HiddenField hdnVatPrcnt = (HiddenField)row.FindControl("hdnVatPrcnt");
                            if (hdnVatPrcnt != null)
                            {
                                hdnVatPrcnt.Value = rRate[0]["Rate"].ToString();
                            }
                            rowUpdate[0]["VatPrcnt"] = rRate[0]["Rate"].ToString();
                            updateRowTotalPrice(rowUpdate[0], "");
                        }
                    }

                    BindData(tblQUT1);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        private void SetItem(GridViewRow row)
        {
            DataTable tblRDR1 = (DataTable)Session["DOTable"];
            Label lblNo = (Label)row.FindControl("lblNo");
            DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
            DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
            DropDownList ddlCorlor = (DropDownList)row.FindControl("ddlColor");
            DataTable dtWhs = GF.GetWarehouseByDealerDepartment(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), Utils.AppConstants.PARTS);
            DataTable dtVatGroup = GF.GetVatGroupByCategory(dbType, "O");
            if (ddlModel != null && ddlProduct != null && ddlCorlor != null)
            {

                DataTable dtItem = GF.GetItem(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlModel.SelectedValue, ddlProduct.SelectedValue, ddlCorlor.SelectedValue);
                GetDefault defaultWS = new GetDefault();
                DataRow[] rowUpdate = null;
                if (dtItem != null && dtItem.Rows.Count == 1)
                {
                    DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                    DataSet defaultInfo = defaultWS.GetDefaultLineInfo(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(),
                        this.txtCustomerCode.Text, dtItem.Rows[0]["ItemCode"].ToString(), 1, poDate, Utils.AppConstants.PARTS);
                    if (defaultInfo != null && defaultInfo.Tables != null && defaultInfo.Tables[0].Rows.Count == 1)
                    {
                        DataRow drDefaultLine = defaultInfo.Tables[0].Rows[0];
                        rowUpdate = tblRDR1.Select("No=" + lblNo.Text);
                        if (rowUpdate.Length == 1)
                        {
                            rowUpdate[0]["ItemCode"] = dtItem.Rows[0]["ItemCode"].ToString();
                            rowUpdate[0]["Dscription"] = dtItem.Rows[0]["ItemName"].ToString();
                            rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                            rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                            rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                            rowUpdate[0]["Quantity"] = 1;

                            rowUpdate[0]["PriceBefDi"] = drDefaultLine["UnitPrice"];
                            rowUpdate[0]["DiscPrcnt"] = drDefaultLine["Discount"];
                            rowUpdate[0]["PriceBefDi"] = drDefaultLine["PriceAfDi"];

                            rowUpdate[0]["VatGroup"] = drDefaultLine["TaxCode"];
                            rowUpdate[0]["VatPrcnt"] = drDefaultLine["TaxRate"];
                            rowUpdate[0]["VatSum"] =
                            rowUpdate[0]["U_Discount"] =
                            rowUpdate[0]["U_IncentiveDiscount"] = 0;
                            rowUpdate[0]["WhsCode"] = drDefaultLine["WhsCode"];

                            updateRowTotalPrice(rowUpdate[0], "");
                        }
                    }
                }
                else
                {
                    rowUpdate = tblRDR1.Select("No=" + lblNo.Text);
                    rowUpdate[0]["ItemCode"] =
                    rowUpdate[0]["Dscription"] = string.Empty;
                    rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                    rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                    rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                    rowUpdate[0]["Quantity"] = 1;

                    rowUpdate[0]["PriceBefDi"] = 0;
                    rowUpdate[0]["DiscPrcnt"] = 0;
                    rowUpdate[0]["PriceBefDi"] = 0;

                    rowUpdate[0]["VatGroup"] = dtVatGroup.Rows.Count > 0 ? dtVatGroup.Rows[0]["Code"].ToString() : string.Empty;
                    rowUpdate[0]["VatPrcnt"] = dtVatGroup.Rows.Count > 0 ? dtVatGroup.Rows[0]["Rate"].ToString() : "0";
                    rowUpdate[0]["VatSum"] =
                    rowUpdate[0]["U_Discount"] =
                    rowUpdate[0]["U_IncentiveDiscount"] = 0;
                    rowUpdate[0]["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;

                    updateRowTotalPrice(rowUpdate[0], "");
                }
                BindData(tblRDR1);
                updateTableTotalPrice(); // Update total Amount
            }
        }

        protected void btnAddItems_Click(object sender, EventArgs e)
        {
            DataTable dtWhs = GF.GetWarehouseByDealerDepartment(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), Utils.AppConstants.PARTS);
            DataTable dtVatGroup = GF.GetVatGroupByCategory(dbType, "O");
            DataTable tbRDR1 = (DataTable)Session["DOTable"];
            DataRow rowNew = tbRDR1.NewRow();
            rowNew["No"] = (tbRDR1.Rows.Count + 1).ToString();
            rowNew["ItemCode"] =
            rowNew["Dscription"] =
            rowNew["U_Model"] =
            rowNew["U_Product"] =
            rowNew["U_Color"] = string.Empty;
            rowNew["Quantity"] = 1;
            rowNew["PriceBefDi"] =
                //rowNew["DiscPrcnt"] =
            rowNew["PriceBefDi"] = 0;

            rowNew["VatGroup"] = dtVatGroup.Rows.Count > 0 ? dtVatGroup.Rows[0]["Code"].ToString() : string.Empty;
            rowNew["VatPrcnt"] = dtVatGroup.Rows.Count > 0 ? dtVatGroup.Rows[0]["Rate"].ToString() : "0";
            rowNew["VatSum"] =
            rowNew["U_Discount"] =
            rowNew["U_IncentiveDiscount"] = 0;

            rowNew["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;

            tbRDR1.Rows.Add(rowNew);
            BindData(tbRDR1);
        }

        private DataTable datatable4Exp()
        {
            DataTable tblPDN1 = (DataTable)Session["DOTable"];

            DataTable dtRecords = new DataTable();

            DataColumn dc = new DataColumn("Model");
            dc.DataType = Type.GetType("System.String");
            dtRecords.Columns.Add(dc);

            dc = new DataColumn("Product");
            dc.DataType = Type.GetType("System.String");
            dtRecords.Columns.Add(dc);

            dc = new DataColumn("Color");
            dc.DataType = Type.GetType("System.String");
            dtRecords.Columns.Add(dc);

            dc = new DataColumn("Item");
            dc.DataType = Type.GetType("System.String");
            dtRecords.Columns.Add(dc);

            dc = new DataColumn("VIN Number");
            dc.DataType = Type.GetType("System.String");
            dtRecords.Columns.Add(dc);

            dc = new DataColumn("Engin Number");
            dc.DataType = Type.GetType("System.String");
            dtRecords.Columns.Add(dc);

            DataRow dr = null;
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

            foreach (DataRow row in tblPDN1.Rows)
            {
                if (GF.GetItemGroupByCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), row["ItemCode"].ToString()).Equals("104")) continue;
                string lsQty = row["Quantity"].ToString();
                int liQty = int.Parse(string.IsNullOrEmpty(lsQty) ? "0" : lsQty.Split('.')[0]);
                if (liQty == 1)
                {
                    dr = dtRecords.NewRow();
                    dr["Model"] = row["U_Model"];
                    dr["Product"] = row["U_Product"];
                    dr["Color"] = row["U_Color"];
                    dr["Item"] = row["ItemCode"];
                    dtRecords.Rows.Add(dr);
                }
                else if (liQty > 1)
                {
                    for (int i = 0; i < liQty; i++)
                    {
                        dr = dtRecords.NewRow();
                        dr["Model"] = row["U_Model"];
                        dr["Product"] = row["U_Product"];
                        dr["Color"] = row["U_Color"];
                        dr["Item"] = row["ItemCode"];
                        dtRecords.Rows.Add(dr);
                    }
                }
            }
            return dtRecords;
        }

        private bool ImportValidation()
        {
            if (this.FileUploadControl.PostedFile == null && this.FileUploadControl.PostedFile.FileName.Length <= 0)
            {
                Session["errorMessage"] = "Please select a Excel file before click on Import button.";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
                return false;
            }
            string lsFileExtension = Path.GetExtension(this.FileUploadControl.PostedFile.FileName);
            if ((!lsFileExtension.Equals(".csv")))
            {
                Session["errorMessage"] = "Invalid file. Please select a .csv file.";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
                return false;
            }
            return true;
        }

        protected void btnImport_Click(object sender, EventArgs e)
        {

            if (ImportValidation())
            {
                DataTable dtExcelRecords = new DataTable();
                string fileLocation = Server.MapPath("~/App_Data/");
                if (this.FileUploadControl.HasFile)
                {
                    string fileName = Path.GetFileName(FileUploadControl.PostedFile.FileName);
                    this.FileUploadControl.SaveAs(fileLocation + fileName); // save file to server
                    dtExcelRecords = Utils.AppConstants.ImportCSVFile(fileName, fileLocation);
                }
                DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                DataTable tblRDR1 = (DataTable)Session["DOTable"];
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                foreach (DataRow r in dtExcelRecords.Rows)
                {
                    LoadItem(poDate, ref tblRDR1, dbType, r["ItemCode"].ToString(), r["Quantity"].ToString(), r["DisCount"].ToString(), r["Price"].ToString());
                }

                if (tblRDR1.Rows.Count > 0)
                    foreach (DataRow dr in tblRDR1.Rows)
                        updateRowTotalPrice(dr, "");
                //ReLoad Data
                BindData(tblRDR1);
                updateTableTotalPrice();


            }
        }

        private void ImportData()
        {
            DataTable tblSRNT = null;
            for (int x = 1; x < GF.FileLines.Count; x++)
            {
                string[] rowData = GF.FileLines[x].ToString().Split(',');
                BuildSRNT(ref tblSRNT, rowData[3], "", rowData[4], DateTime.Now.ToString("dd/MM/yyyy"), rowData[5], 1, "01", ConvertDocType.Get2String(DocType.DELIVERY), "", "");
            }

            Session["tblPARTSRNT"] = tblSRNT;
        }

        protected void btnGetTemplate_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = datatable4Exp();

                if (dt != null)
                {
                    Response.AddHeader("Content-Disposition", "attachment;filename=GR.csv");
                    Response.ContentType = "text/csv";
                    int iColCount = dt.Columns.Count;

                    for (int i = 0; i < iColCount; i++)
                    {
                        Response.Write("\"" + dt.Columns[i] + "\"");
                        if (i < iColCount - 1)
                        {
                            Response.Write(",");
                        }
                    }

                    Response.Write(Environment.NewLine);
                    // Now write all the rows.
                    for (int x = 0; x < dt.Rows.Count; x++)
                    {
                        for (int i = 0; i < iColCount; i++)
                        {
                            if (!Convert.IsDBNull(dt.Rows[x][i])) Response.Write("\"" + dt.Rows[x][i].ToString() + "\"");
                            if (i < iColCount - 1) Response.Write(",");
                        }
                        Response.Write(Environment.NewLine);
                    }
                    Response.End();
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void btnGetImportTemplate_Click(object sender, EventArgs e)
        {
            try
            {
                string filePath = Server.MapPath(SupportDocs.fileImportParts);
                string downloadName = "Parts.csv";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + downloadName + "");
                Response.ContentType = "text/csv";
                Response.TransmitFile(filePath);
                Response.End();
            }
            catch (Exception ex)
            {
            }
        }

        protected void btnDraft_Click(object sender, EventArgs e)
        {
            try
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                if (string.IsNullOrEmpty(txtPostingDate.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Posting Date.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtPostingDate.Focus();
                    return;
                }

                if (string.IsNullOrEmpty(txtDocDate.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Document Date.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtDocDate.Focus();
                    return;
                }

                if (string.IsNullOrEmpty(txtDeliveryDate.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Delivery Date.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtDeliveryDate.Focus();
                    return;
                }

                if (string.IsNullOrEmpty(txtCustomerCode.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Customer Code.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtCustomerCode.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(this.txtVSMSONumber.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing SO Number.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtVSMSONumber.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(this.txtDebitNoteNo.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Debit Note No.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtDebitNoteNo.Focus();
                    return;
                }
                else
                {
                    string lsNumAtCard = GF.GetSingleValue(dbType, " SELECT U_DebitNote FROM ODLN WHERE U_DebitNote = '" + this.txtDebitNoteNo.Text.Trim() + "'", "U_DebitNote");
                    if (!string.IsNullOrEmpty(lsNumAtCard))
                    {
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('The Debit Note No. existed.','');", true);
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                        this.txtDebitNoteNo.Focus();
                        return;
                    }
                }

                String requestXML = _collectData(true, "15");
                if (requestXML == "") return;

                bool isUpdate = false;
                if (this.hdnDocEntry.Value.Length > 0 && this.hdnIsDraft.Value == "1")
                {
                    isUpdate = true;
                }
                Transaction ts = new Transaction();
                DataSet ds = ts.CreateMarketingDocument(requestXML, ConvertDocType.Get2String(DocType.DELIVERY), this.hdnDocEntry.Value, isUpdate, dbType);

                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void chkPromotion_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < this.grvSO.Rows.Count; i++)
            {

                Label lblItemCode = (Label)this.grvSO.Rows[i].FindControl("lblItemCode");
                TextBox txtUnitPrice = (TextBox)this.grvSO.Rows[i].FindControl("txtUnitPrice");
                TextBox txtPromotionPrice = (TextBox)this.grvSO.Rows[i].FindControl("txtPromotionPrice");
                DataTable tb = (DataTable)Session["DOTable"];
                if (tb != null)
                {
                    DataRow[] r = tb.Select("ItemCode = '" + lblItemCode.Text + "'");
                    if (r.Length > 0)
                    {
                        if (this.chkPromotion.Checked)
                        {
                            this.grvSO.Columns[7].Visible = false;
                            r[0]["U_PromotionPrice"] = txtUnitPrice.Text;
                            txtPromotionPrice.Text = txtUnitPrice.Text;
                        }
                        else
                        {
                            this.grvSO.Columns[7].Visible = true;
                            r[0]["U_PromotionPrice"] = 0;
                            txtPromotionPrice.Text = "0";
                        }
                    }
                }
            }
        }
        protected void txtPromtionPrice_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtPromotionPrice = (TextBox)row.FindControl("txtPromotionPrice");
                if (txtPromotionPrice.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Price');", true);
                    txtPromotionPrice.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["DOTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["U_PromotionPrice"] = GF.FormatNumeric(txtPromotionPrice.Text, "PriceDec");
                    }
                }


                BindData(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        public String UpdateStatus(string UpdateStatus, string TblHeaderName)
        {
            try
            {
                //Update table header
                DataTable dtHeader = new DataTable(TblHeaderName);
                dtHeader.Columns.Add("DocEntry");
                dtHeader.Columns.Add("U_OrderConfirm");
                DataRow drHeader = dtHeader.NewRow();
                drHeader["DocEntry"] = int.Parse(this.txtDONo.Text);
                drHeader["U_OrderConfirm"] = UpdateStatus;
                dtHeader.Rows.Add(drHeader);
                dtHeader.TableName = TblHeaderName;
                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");
                ds.Tables.Add(dtHeader.Copy());
                return objInfo.ToXMLStringFromDS(ConvertDocType.Get2String(DocType.DELIVERY), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnPrint_Click(object sender, EventArgs e)
        {
            Transaction ts = new Transaction();
            string requestXML = UpdateStatus("21", "ODLN");
            if (requestXML == "") return;
            ts.CreateMarketingDocument(requestXML, ConvertDocType.Get2String(DocType.DELIVERY), this.txtDONo.Text, true, dbType);
        }
    }
}